package wuxianshua.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SpilderService {

    @Autowired
    private HttpClient httpClient;

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    //下载网页
    private  String downLoad(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        String cookie = redisTemplate.opsForValue().get("cookie");
        System.out.println("cooike: "+cookie);
        httpGet.setHeader("Cookie",cookie);
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");
        httpGet.setHeader("content-type","text/html; charset=UTF-8");
        httpGet.setHeader("x-requested-with","XMLHttpRequest");
        HttpResponse resp = httpClient.execute(httpGet);
        return EntityUtils.toString(resp.getEntity());
    }


    public  int  spilder() throws IOException {
        String s = downLoad("https://featurize.cn/bus/api/v1/available_instances?page=0&gpu106=false&gpu1660=false&gpu1080=false&gpu2080=false&gpu3080=true&gpu3090=true&idle=true");
        JSONObject jsonObject = JSON.parseObject(s);
        System.out.println(jsonObject);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray records = data.getJSONArray("records");
        return records.size();
    }
}